/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.jjsoft.disco.gco.view;

import com.jjsoft.disco.gco.mdl.Ingrediente;
import com.jjsoft.disco.gco.mdl.Producto;
import com.jjsoft.disco.gco.mdl.Unidadmedida;
import com.jjsoft.disco.gco.ngc.UnidadMedidaManager;
import com.jjsoft.disco.gco.util.CSelecciones;
import com.jjsoft.disco.gco.util.MiModelo;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.UIManager;

/**
 *
 * @author Johnny
 */
public class VAgregarIngredientes extends javax.swing.JFrame {

    /**
     * Creates new form VAgregarIngredientes
     */
    MiModelo modelo = new MiModelo();
    List<Ingrediente> listaIngredientes;
    List<Unidadmedida> listaUnidades;
    Ingrediente ingrediente;
    JTextField texto;

    public VAgregarIngredientes(List<Ingrediente> listaIngredientes, JTextField texto) {
        initComponents();
        this.listaIngredientes = listaIngredientes;
        this.texto=texto;
        
        String[] identificadores = new String[]{"Ingrediente", "Unidad de Medida", "Cantidad"};
        modelo.setColumnIdentifiers(identificadores);
        dtgProductos.setModel(modelo);
        dtgProductos.getColumn("Cantidad").setPreferredWidth(50);
        dtgProductos.getColumn("Ingrediente").setPreferredWidth(250);
        if(listaIngredientes.size()>0)
        {
            for(int i=0;i<listaIngredientes.size();i++)
            {
                agregarIngrediente(listaIngredientes.get(i));
            }
        }
        cargarCombo();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        lblTitulo = new javax.swing.JLabel();
        jLabel1 = new javax.swing.JLabel();
        txtIngrediente = new javax.swing.JTextField();
        cmdSeleccionar = new javax.swing.JButton();
        jLabel2 = new javax.swing.JLabel();
        cboUMedida = new javax.swing.JComboBox();
        jLabel3 = new javax.swing.JLabel();
        txtCantidad = new javax.swing.JTextField();
        cmdAgregar = new javax.swing.JButton();
        cmdAceptar = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        dtgProductos = new javax.swing.JTable();
        cmdQuitar = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        lblTitulo.setFont(new java.awt.Font("Ubuntu", 0, 18)); // NOI18N
        lblTitulo.setForeground(new java.awt.Color(26, 45, 245));
        lblTitulo.setText("Agregue Ingredientes al Coctel");

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel1.setForeground(new java.awt.Color(51, 51, 51));
        jLabel1.setText("Ingrediente:");

        txtIngrediente.setEditable(false);
        txtIngrediente.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtIngredienteActionPerformed(evt);
            }
        });

        cmdSeleccionar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/search-database.png"))); // NOI18N
        cmdSeleccionar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmdSeleccionarActionPerformed(evt);
            }
        });

        jLabel2.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel2.setForeground(new java.awt.Color(51, 51, 51));
        jLabel2.setText("U. Medida:");

        jLabel3.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel3.setForeground(new java.awt.Color(51, 51, 51));
        jLabel3.setText("Cantidad:");

        cmdAgregar.setText("Agregar");
        cmdAgregar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmdAgregarActionPerformed(evt);
            }
        });

        cmdAceptar.setText("Aceptar");
        cmdAceptar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmdAceptarActionPerformed(evt);
            }
        });

        dtgProductos.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {},
                {},
                {},
                {}
            },
            new String [] {

            }
        ));
        dtgProductos.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        jScrollPane1.setViewportView(dtgProductos);

        cmdQuitar.setText("Quitar");
        cmdQuitar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmdQuitarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addGroup(layout.createSequentialGroup()
                                .addGap(86, 86, 86)
                                .addComponent(lblTitulo))
                            .addGroup(layout.createSequentialGroup()
                                .addGap(27, 27, 27)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                    .addComponent(jLabel2)
                                    .addComponent(jLabel1)
                                    .addComponent(jLabel3))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(layout.createSequentialGroup()
                                        .addComponent(txtIngrediente, javax.swing.GroupLayout.PREFERRED_SIZE, 103, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                        .addComponent(cmdSeleccionar, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addGap(0, 0, Short.MAX_VALUE))
                                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                            .addComponent(txtCantidad, javax.swing.GroupLayout.Alignment.LEADING)
                                            .addComponent(cboUMedida, 0, 103, Short.MAX_VALUE))
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(cmdAgregar)
                                        .addGap(65, 65, 65)))))
                        .addGap(0, 83, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(cmdQuitar)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(cmdAceptar)))))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(lblTitulo)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(cmdSeleccionar, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel1)
                        .addComponent(txtIngrediente, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(cboUMedida, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(txtCantidad, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(cmdAgregar))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 199, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(cmdAceptar)
                    .addComponent(cmdQuitar))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        setSize(new java.awt.Dimension(455, 405));
        setLocationRelativeTo(null);
    }// </editor-fold>//GEN-END:initComponents

    private void cmdSeleccionarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmdSeleccionarActionPerformed
        // TODO add your handling code here:
        CSelecciones.producto = null;
        CSelecciones.texto1 = txtIngrediente;
        new VSeleccionArticulo(false).show();
    }//GEN-LAST:event_cmdSeleccionarActionPerformed

    private void txtIngredienteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtIngredienteActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_txtIngredienteActionPerformed

    private void cmdAgregarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmdAgregarActionPerformed
        // TODO add your handling code here:
        try {
            Integer.parseInt(txtCantidad.getText());
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(rootPane, "Ingrese una cantidad correcta", "Error", JOptionPane.ERROR_MESSAGE);
            return;
        }
        if (CSelecciones.producto != null) {
            boolean existe = false;
            for (int i = 0; i < listaIngredientes.size(); i++) {
                if (listaIngredientes.get(i).getIdIngredienteProducto().equals(CSelecciones.producto)) {
                    listaIngredientes.get(i).setCantidad(listaIngredientes.get(i).getCantidad() + Integer.parseInt(txtCantidad.getText()));
                    dtgProductos.setValueAt(listaIngredientes.get(i).getCantidad(), i, 2);
                    existe = true;
                    CSelecciones.producto = null;
                    txtCantidad.setText("");
                    txtIngrediente.setText("");
                    cboUMedida.setSelectedIndex(0);
                }
            }
            if (!existe) {
                agregarIngrediente();
            }
        } else {
            JOptionPane.showMessageDialog(rootPane, "No ha seleccionado un ingrediente", "Error", JOptionPane.ERROR_MESSAGE);
        }
    }//GEN-LAST:event_cmdAgregarActionPerformed

    private void cmdQuitarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmdQuitarActionPerformed
        // TODO add your handling code here:
        if (dtgProductos.getSelectedRow() != -1) {
            listaIngredientes.remove(dtgProductos.getSelectedRow());
            modelo.removeRow(dtgProductos.getSelectedRow());
        } else {
            JOptionPane.showMessageDialog(rootPane, "Primero seleccione un ingrediente", "Error", JOptionPane.ERROR_MESSAGE);
        }
    }//GEN-LAST:event_cmdQuitarActionPerformed

    private void cmdAceptarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmdAceptarActionPerformed
        // TODO add your handling code here:
        this.texto.setText(String.valueOf(listaIngredientes.size()));
        this.dispose();
    }//GEN-LAST:event_cmdAceptarActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(VAgregarIngredientes.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(VAgregarIngredientes.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(VAgregarIngredientes.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(VAgregarIngredientes.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (Exception e) {
            System.out.println("Error setting native LAF: " + e);
        }
        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new VAgregarIngredientes(null,null).setVisible(true);
            }
        });
    }

    private void agregarIngrediente() {
        String[] Ingrediente = new String[]{CSelecciones.producto.getIdCategoria().getNombre() + " " + CSelecciones.producto.getDescripcion(), listaUnidades.get(cboUMedida.getSelectedIndex()).getNombre(), txtCantidad.getText()};
        modelo.addRow(Ingrediente);
        ingrediente = new Ingrediente();
        ingrediente.setCantidad(Integer.parseInt(txtCantidad.getText()));
        ingrediente.setIdIngredienteProducto(CSelecciones.producto);
        ingrediente.setIdUnidadMedida(listaUnidades.get(cboUMedida.getSelectedIndex()));
        listaIngredientes.add(ingrediente);
        CSelecciones.producto = null;
        txtCantidad.setText("");
        txtIngrediente.setText("");
        cboUMedida.setSelectedIndex(0);
    }
    private void agregarIngrediente(Ingrediente ingrediente)
    {
        String[] Ingrediente = new String[]{ingrediente.getIdIngredienteProducto().getIdCategoria().getNombre()+" "+ingrediente.getIdIngredienteProducto().getDescripcion(),ingrediente.getIdUnidadMedida().getNombre(),ingrediente.getCantidad().toString()};
        modelo.addRow(Ingrediente);
        
    }

    private void cargarCombo() {
        UnidadMedidaManager umManager = new UnidadMedidaManager();
        listaUnidades = umManager.listarUnidadesMedida();
        for (int i = 0; i < listaUnidades.size(); i++) {
            cboUMedida.addItem(listaUnidades.get(i).getNombre());
        }
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JComboBox cboUMedida;
    private javax.swing.JButton cmdAceptar;
    private javax.swing.JButton cmdAgregar;
    private javax.swing.JButton cmdQuitar;
    private javax.swing.JButton cmdSeleccionar;
    private javax.swing.JTable dtgProductos;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JLabel lblTitulo;
    private javax.swing.JTextField txtCantidad;
    private javax.swing.JTextField txtIngrediente;
    // End of variables declaration//GEN-END:variables
}
